package com.study_security.service.impl;

import com.study_security.domain.ResponseResult;
import com.study_security.service.SmsService;
import com.study_security.utils.SmsUtils;
import com.study_security.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private RedisCache redisCache;

    private static final String SIGN_NAME = "工大软件工程实训"; // 根据实际情况修改
    private static final String TEMPLATE_CODE = "SMS_478015089"; // 根据实际情况修改
    private static final String TEMPLATE_CODE_NOTIFICATION = "SMS_478060093"; // 通知短信模板
    private static final int CODE_EXPIRE_TIME = 5 * 60; // 验证码有效期，单位秒

    @Override
    public ResponseResult sendVerificationCodeByPhone(String phone) {
        // 生成6位随机验证码
       String code = String.format("%06d", new Random().nextInt(999999));
        //String code ="你的任务快截";
        System.out.println(code);
        String templateParam = "{\"code\":\"" + code + "\"}";

        try {
            smsUtils.sendSms(SIGN_NAME, TEMPLATE_CODE, phone, templateParam);
            // 将验证码存入Redis，键格式为verify:phone:phoneNumber，设置过期时间
            String phoneKey = "verify:phone:" + phone;
            redisCache.setCacheObject(phoneKey, code, CODE_EXPIRE_TIME, TimeUnit.SECONDS);
        } catch (Exception e) {
            // 推荐使用日志记录异常，而不是直接返回异常消息
            // 例如：logger.error("短信验证码发送失败", e);
            return new ResponseResult(500, "短信验证码发送失败：" + e.getMessage());
        }

        return new ResponseResult(200, "短信验证码发送成功");
    }

    @Override
    public ResponseResult sendNotificationByPhone(String phone, String messageContent) {
        // 构建通知短信的参数
        String templateParam = "{\"message\":\"" + messageContent + "\"}";

        try {
            smsUtils.sendSms(SIGN_NAME, TEMPLATE_CODE_NOTIFICATION, phone, templateParam);
        } catch (Exception e) {
            return new ResponseResult(500, "通知短信发送失败：" + e.getMessage());
        }

        return new ResponseResult(200, "通知短信发送成功");
    }
}
